package controller

import (
	"gitee.com/molonglove/goboot/gin"
	"github.com/gorilla/websocket"
	"helper-api/app/constant"
	"helper-api/app/models/response"
	"helper-api/core"
	"net/http"
)

var Ws = new(WsController)

type WsController struct{}

func (w *WsController) WebSocket(c *gin.Context) {
	var (
		upGrader websocket.Upgrader
		ws       *websocket.Conn
		userId   int64
		isValid  bool
		err      error
	)

	isValid = c.GetBool(constant.WSHeaderKey)
	userId = c.GetInt64(constant.HeaderUserKey)
	upGrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return isValid
		},
	}
	if ws, err = upGrader.Upgrade(c.Writer, c.Request, nil); err != nil {
		core.Log.Error("启动WebSocket失败 => %s", err.Error())
		c.JSON(http.StatusOK, response.ResultCustom(response.NewBusinessError(response.WsCreateError)))
		return
	}
	core.WS.AddClient(userId, ws)
}
